﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Ext.Net;
using System.Text;

public partial class UsersModuleRights2 : ExtBaseRpt
{
    MyDbHelper mydb = new MyDbHelper();
    string mid;
    protected void Page_Load(object sender, EventArgs e)
    {
        mid = Request.Params["mid"];
        if (!IsPostBack)
        {
            BinUserList(this.txtuser.Text);
            IniModleTree();
            InsActLog(mid, "浏览");
        }
    }

    public void IniModleTree()
    {
        this.TreePanel1.Root.Clear();
        string sql = "select * from sys_modules where parentid = 0 order by mindx";
        DataSet ds = mydb.DM_GetDateSet(sql);
        Node mNode = new Node();
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                Node node = new Node();
                node.NodeID = dr["mid"].ToString();
                node.Text = "[" + dr["mindx"].ToString() + "]" + dr["modulename"].ToString();
                node.Qtip = dr["modulename"].ToString();
                node.IconCls = "Folder";
                mNode.Children.Add(node);
                AddChildNode(node, dr["mid"].ToString());
            }
            this.TreePanel1.Root.Add(mNode);
        }
    }
    private void AddChildNode(Node node, string parentid)
    {
        string sql = "select * from sys_modules where parentid = " + parentid + " order by mindx";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                Node childNode = new Node();
                childNode.NodeID = dr["mid"].ToString();
                childNode.Text = "[" + dr["mindx"].ToString() + "]" + dr["modulename"].ToString();
                childNode.Qtip = dr["modulename"].ToString();
                node.Children.Add(childNode);
                AddChildNode(childNode, dr["mid"].ToString());
            }
        }
    }
    protected void BtnFindUser(object sender, DirectEventArgs e)
    {
        BinUserList(this.txtuser.Text);
    }
    public void BinUserList(string param)
    {
        string str = "";
        if (param != "")
        {
            str += " and usercode like '%" + param + "%' or username like '%" + param + "%'";
        }
        this.Store2.DataSource =  mydb.DM_GetDateSet("select userid,usercode,username from sys_loginuser where 1=1" + str);
        this.Store2.DataBind();
    }

    private void bindldyout()
    {
        if (string.IsNullOrEmpty(hf_tree_id.Value.ToString()))
        {
            return;
        }
        //绑定全局布局
        string sql = @"select lid,mid,lindx,fieldname,fielddisplay,fieldwidth,fieldvisible,gridfoot,datatype,showtype
        from sys_moduleslayout where mid =" + hf_tree_id.Value;
        this.Store3.DataSource = mydb.DM_GetDateSet(sql);
        this.Store3.DataBind();

        
        if (string.IsNullOrEmpty(hf_user_id.Value.ToString()))
        {
            return;
        }
         sql = @"select mu_id,fid,lindx,fieldname,fielddisplay,mu_visible,fieldwidth from sys_moduleslayout a 
                    inner join sys_modulesuserlayout b on b.fid =lid 
                    where a.mid = " + hf_tree_id.Value
                  + " and userid=" + hf_user_id.Value;
        this.Store1.DataSource = mydb.DM_GetDateSet(sql);
        this.Store1.DataBind();
        DataSet ds = mydb.DM_GetDateSet("select * from sys_modulerights where mid =" + hf_tree_id.Value + " and userid=" + hf_user_id.Value);
        if (ds.Tables[0].Rows.Count > 0)
        {
            this.M_Browse.Checked = (ds.Tables[0].Rows[0]["M_Browse"].ToString().ToLower() == "true" ? true : false);
            this.M_Export.Checked = (ds.Tables[0].Rows[0]["M_Export"].ToString().ToLower() == "true" ? true : false);
        }
        else
        {
            this.M_Browse.Checked = false;
            this.M_Export.Checked = false;
        }
    }

    protected void Cell_Click(object sender, DirectEventArgs e)
    {
        RowSelectionModel sm = this.GridPanel2.GetSelectionModel() as RowSelectionModel;
        this.hf_user_id.Value = sm.SelectedRow.RecordID;
        //X.Msg.Alert("Submit", "You have submitted " + hf_user_id.Value + " nodes").Show();
        bindldyout();
    }
    protected void Tree_Row_Click(object sender, DirectEventArgs e)
    {
        TreeSelectionModel sm = this.TreePanel1.GetSelectionModel() as TreeSelectionModel;
        this.hf_tree_id.Value = sm.SelectedRow.RecordID;
        //插入当前用户布局
        string sql = @"if not exists(select top 1 * from sys_modulesuserlayout where mid=" + hf_tree_id.Value.ToString() 
                    + " and userid ='" + hf_user_id.Value + @"')
                        insert into sys_modulesuserlayout(userid,mid,fid,mu_visible,mu_readonly)
                        select '" + hf_user_id.Value.ToString() + @"',mid,lid,1,1 from sys_moduleslayout 
                        where mid=" + hf_tree_id.Value.ToString();
        mydb.DM_ExecuteNonQuery(sql);
        bindldyout();
        //X.Msg.Alert("Submit", "You have submitted " + sm.SelectedRow.RecordID + " nodes").Show();
    }
    protected void MyData_Refresh(object sender, StoreReadDataEventArgs e)
    {
        BinUserList(this.txtuser.Text);
    }
    protected void MyData_Refresh2(object sender, StoreReadDataEventArgs e)
    {
        bindldyout();
    }
    protected void Command(object sender, DirectEventArgs e)
    {
        var command = e.ExtraParams["command"].ToString();
        var Id = e.ExtraParams["Id"].ToString();
        X.Msg.Alert("Command", Id + " : " + command).Show();
        if (command == "Delete")
        {
            //this.txtuser.Text = command;
            
        }
        
        
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void RightChangeSave(string mid,string userid,string key,string val)
    {
        //X.Msg.Alert("Submit", val).Show();
        if (userid == "")
        {
            X.Msg.Alert("提示", "请选择用户").Show();
            return;
        }
        if (mid == "")
        {
            X.Msg.Alert("提示", "请选择模块").Show();
            return;
        }
        //string modetype = mydb.DM_GetExecuteScalarObj("select moduletype from sys_modules where mid =" + mid).ToString();
        //if (modetype != "1")
        //{
        //    X.Msg.Alert("提示", "当前节点不是功能菜单，无法设置权限,只能设置布局权限！").Show();
        //    return;
        //}
        string sql = @"if not exists(select * from sys_modulerights where mid=" + mid + " and userid=" + userid + @")
                        insert into sys_modulerights(userid,mid,creator,M_Browse)values("
                         + userid + "," + mid + ",'" + Session["UserID"] + @"',0)
                        else 
                        update sys_modulerights set " + key + "='" + val + "',modifydate='" + DateTime.Now.ToString() + "' where mid="
            + mid + " and userid=" + userid;
        mydb.DM_ExecuteNonQuery(sql);
        //X.Msg.Alert("Submit", sql).Show();
    }

    protected void BatchDel_Click(object sender, DirectEventArgs e)
    {
        RowSelectionModel sm = this.GridPanel1.GetSelectionModel() as RowSelectionModel;

        foreach (SelectedRow row in sm.SelectedRows)
        {
            mydb.DM_ExecuteNonQuery("delete from sys_modulesuserlayout where mu_id="+row.RecordID);
        }
        bindldyout();
    }
    protected void BatchVisb_Click(object sender, DirectEventArgs e)
    {
        
    }
    protected void BatchDel2_Click(object sender, DirectEventArgs e)
    {
        RowSelectionModel sm = this.GridPanel3.GetSelectionModel() as RowSelectionModel;

        foreach (SelectedRow row in sm.SelectedRows)
        {
            mydb.DM_ExecuteNonQuery("delete from sys_moduleslayout where lid=" + row.RecordID);
        }
        bindldyout();
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void Edit(int id,int fid, string field, string oldValue, string newValue, object customer)
    {
        //string message = "<b>Property:</b> {0}<br /><b>Field:</b> {1}<br /><b>Old Value:</b> {2}<br /><b>New Value:</b> {3}";
        // Send Message...
        //X.Msg.Notify(new NotificationConfig()
        //{
        //    Title = "Edit Record #" + id.ToString(),
        //    Html = string.Format(message, id, field, oldValue, newValue),
        //    Width = 250
        //}).Show();
        //更新到数据库
        string sql = "";
        if (field == "mu_visible")
        {
            sql = "update sys_modulesuserlayout set mu_visible=" + (newValue.ToLower() == "true" ? 1 : 0)
            + " where mu_id=" + id;
        }
        else
        {
            sql = "update sys_moduleslayout set " + field + "='" + newValue + "' where LID=" + fid;
        }
        //X.Msg.Alert("Submit", "You have submitted " + sql + " nodes").Show();
        if (mydb.DM_ExecuteNonQuery(sql) != -1)
        {
            this.GridPanel1.GetStore().GetById(id).Commit();
        }
        else
        {
            X.Msg.Notify(new NotificationConfig()
            {
                Title = "消息提示",
                Html = "修改失败！",
                Width = 250
            }).Show();
        }
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void Edit2(int fid, string field, string oldValue, string newValue, object customer)
    {
        if (mydb.DM_ExecuteNonQuery("update sys_moduleslayout set " + field + "='" + newValue + "' where LID=" + fid) != -1)
        {
            this.GridPanel3.GetStore().GetById(fid).Commit();
            if (field == "fielddisplay")
            {
                LayoutInfo lt = JSON.Deserialize<LayoutInfo>(customer.ToString());
                mydb.DM_ExecuteNonQuery("Exc_FieldDisPlay '" + lt.fieldname + "','" + lt.fielddisplay + "'");
            }
            if (field == "fieldvisible")
            {
                string sql = "update sys_modulesuserlayout set mu_visible = '"+newValue+"' where fid="+fid;
                mydb.DM_ExecuteNonQuery(sql);
            }
        }
        else
        {
            X.Msg.Notify(new NotificationConfig()
            {
                Title = "消息提示",
                Html = "修改失败！",
                Width = 250
            }).Show();
        }
    }

    public class LayoutInfo{
        public string lid{get;set;}
        public string fieldname{get;set;}
        public string fielddisplay{get;set;}
        public string fieldwidth{get;set;}
        public string fieldvisible{get;set;}
        public string gridfoot{get;set;}
        public string datatype{get;set;}
    }
}